package com.ruibang.glass.purchase.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.Constants;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.common.domain.camunda.BpmProcessInstanceCreate;
import com.ruibang.glass.common.domain.camunda.BpmProcessInstanceStatus;
import com.ruibang.glass.common.domain.camunda.BpmTaskApproveReq;
import com.ruibang.glass.common.domain.file.FileBusiness;
import com.ruibang.glass.common.domain.material.MaterialManagement;
import com.ruibang.glass.purchase.constant.PurchaseErrorCode;
import com.ruibang.glass.purchase.domain.req.PurchaseContractsReq;
import com.ruibang.glass.purchase.entity.*;
import com.ruibang.glass.purchase.feign.CamundaApi;
import com.ruibang.glass.purchase.feign.FileApi;
import com.ruibang.glass.purchase.feign.MaterialApi;
import com.ruibang.glass.purchase.mapper.*;
import com.ruibang.glass.purchase.service.CommonService;
import com.ruibang.glass.purchase.service.ProcureReportBiddersService;
import com.ruibang.glass.purchase.service.PurchaseApprovalSupplierService;
import com.ruibang.glass.purchase.service.PurchaseContractsService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.constant.CommonConstant;
import com.teaming.cloud.framework2.common.exception.ServiceException;
import com.teaming.cloud.framework2.common.model.ResultBody;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruibang.glass.common.constants.Constants.FINISH_NODE_KEY;

/**
 * <p>
 * 采购合同信息表 服务实现类
 * </p>
 *
 * @author mameng
 * @since 2024-03-27
 */
@Service
public class PurchaseContractsServiceImpl extends ServiceImpl<PurchaseContractsMapper, PurchaseContracts> implements PurchaseContractsService {

    @Autowired
    private PurchaseContractProductsMapper gPurchaseContractProductsMapper;

    @Autowired
    private FileApi fileApi;

    @Autowired
    private RedisSingleService redisService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private CamundaApi camundaApi;

    @Autowired
    private MaterialApi materialApi;


    @Autowired
    private PurchaseApprovalSupplierService purchaseApprovalSupplierService;

    @Autowired
    private ProcureReportBiddersMapper reportBiddersMapper;

    @Autowired
    private PurchaseOrderDetailsMapper purchaseOrderDetailsMapper;
    @Autowired
    private PurchaseRelatedProductMapper purchaseRelatedProductMapper;
    @Autowired
    private PurchaseApprovalListMapper purchaseApprovalListMapper;

    private static final String PURCHASE_HTFJ = "sale_contract_htfj_file";//合同附件上传
    private static final String PURCHASE_ZBSM = "sale_contract_zbsm_file";//增补说明上传
    private static final String PURCHASE_ZBFJ = "sale_contract_zbfj_file";//增补附件上传
    private static final String PURCHASE_QZFJ = "sale_contract_qzfj_file";//签章合同上传
    private static final String PURCHASE_DELETE_FILE = "sale_contract_qzfj_file";//废止合同上传

    @Override
    public IPage<PurchaseContracts> getPage(PurchaseContractsReq purchaseContractsReq) {
        IPage<PurchaseContracts> page = baseMapper.getPage(new Page<>(purchaseContractsReq.getPageNo(), purchaseContractsReq.getPageSize()), purchaseContractsReq);

        if (CollectionUtils.isEmpty(page.getRecords())) {
            return page;
        }
        Map<Object, Object> userMap = redisService.hmget(RedisKey.USER_GROUP_TYPE);
        List<String> businessKeys = page.getRecords().stream().map(PurchaseContracts::getId).collect(Collectors.toList());
        Map<String, BpmProcessInstanceStatus> processMap = null;
        //获取业务流程状态
        ResultBody<List<BpmProcessInstanceStatus>> resultBody = camundaApi.queryProcessInstanceStatus(businessKeys);
        if (resultBody != null && CollectionUtils.isNotEmpty(resultBody.getData())) {
            processMap = resultBody.getData().stream().collect(Collectors.toMap(bp -> bp.getBusinessKey(), bp -> bp, (bp1, bp2) -> bp1));
        }
        for (PurchaseContracts qualityContact : page.getRecords()) {
            if (processMap != null && processMap.get(qualityContact.getId()) != null) {
                BpmProcessInstanceStatus process = processMap.get(qualityContact.getId());
                qualityContact.setProcessId(process.getProcessInstanceId());
                qualityContact.setNodeName(process.getNodeName());
                if (StringUtils.isNotBlank(process.getUserId())) {
                    if (process.getUserId().indexOf(CommonConstant.SpecialSign.COMMA.getName()) != -1) {
                        String[] userIds = process.getUserId().split(CommonConstant.SpecialSign.COMMA.getName());
                        StringBuilder userName = new StringBuilder();
                        int size = userIds.length;
                        for (int i = 0; i < size; i++) {
                            String name = userMap.get(userIds[i]) == null ? "" : userMap.get(userIds[i]).toString();
                            if (i == size - 1) {
                                userName.append(name);
                            } else {
                                userName.append(name).append(CommonConstant.SpecialSign.COMMA.getName());
                            }
                        }
                        qualityContact.setApproveUserId(process.getUserId());
                        qualityContact.setApproveUser(userName.toString());
                    } else {
                        qualityContact.setApproveUserId(process.getUserId());
                        qualityContact.setApproveUser(userMap.get(process.getUserId()) == null ? "" : userMap.get(process.getUserId()).toString());
                    }
                }
            }
        }
        return page;
    }

    /**
     * 新增合同流程
     *
     * @param purchaseContracts
     */
    @Override
    public void addPurchaseContracts(PurchaseContracts purchaseContracts) {
        if (StringUtils.isNotBlank(purchaseContracts.getProjectNumber())) {
            String isUsed = "";
            if (CommonConstant.ONE_STR.equals(purchaseContracts.getContractType())) {
                isUsed = reportBiddersMapper.getUsedByNumber(purchaseContracts.getProjectNumber(),purchaseContracts.getSupplierId());
            } else {
                isUsed = purchaseApprovalListMapper.getFrameUsedByNumber(purchaseContracts.getProjectNumber());
            }

            if (StringUtils.isBlank(isUsed)) {
                throw new ServiceException(PurchaseErrorCode.SELECT_PROJECT_IS_USED.getCode(), PurchaseErrorCode.SELECT_PROJECT_IS_USED.getMsg());
            } else {
                if (CommonConstant.ONE_STR.equals(isUsed)) {
                    throw new ServiceException(PurchaseErrorCode.SELECT_PROJECT_IS_USED.getCode(), PurchaseErrorCode.SELECT_PROJECT_IS_USED.getMsg());
                }
            }
        } else {
            throw new ServiceException(PurchaseErrorCode.PROJECT_NUMBER_IS_NOT_NULL.getCode(), PurchaseErrorCode.PROJECT_NUMBER_IS_NOT_NULL.getMsg());
        }

        purchaseContracts.setQzStatus(CommonConstant.ONE_STR);
        purchaseContracts.setApproveStatus(CommonConstant.ZERO_STR);
        purchaseContracts.setId(null);
        baseMapper.insert(purchaseContracts);
        if (CollectionUtils.isNotEmpty(purchaseContracts.getHtfjFileIdList())) {
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setAttribute(PURCHASE_HTFJ);
            fileBusiness.setFileIds(purchaseContracts.getHtfjFileIdList());
            fileBusiness.setBusinessId(purchaseContracts.getId());
            fileApi.updateBusinessById(fileBusiness);
        }

        if (CollectionUtils.isNotEmpty(purchaseContracts.getZbsmFileIdList())) {
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setAttribute(PURCHASE_ZBSM);
            fileBusiness.setFileIds(purchaseContracts.getZbsmFileIdList());
            fileBusiness.setBusinessId(purchaseContracts.getId());
            fileApi.updateBusinessById(fileBusiness);
        }

        if (CollectionUtils.isNotEmpty(purchaseContracts.getZbfjFileIdList())) {
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setAttribute(PURCHASE_ZBFJ);
            fileBusiness.setFileIds(purchaseContracts.getZbfjFileIdList());
            fileBusiness.setBusinessId(purchaseContracts.getId());
            fileApi.updateBusinessById(fileBusiness);
        }
        if (CollectionUtils.isNotEmpty(purchaseContracts.getPurchaseContractProductsList())) {
            for (PurchaseContractProducts purchaseContractProducts : purchaseContracts.getPurchaseContractProductsList()) {
                purchaseContractProducts.setId(null);
                purchaseContractProducts.setContractId(purchaseContracts.getId());
                gPurchaseContractProductsMapper.insert(purchaseContractProducts);
            }
        }

        reportBiddersMapper.updateReportUsed(purchaseContracts.getProjectNumber(), purchaseContracts.getSupplierId(),CommonConstant.ONE_STR);
        purchaseApprovalListMapper.updateApprovalSupplier(purchaseContracts.getProjectNumber(), purchaseContracts.getSupplierId(),CommonConstant.ONE_STR);
    }

    /**
     * 上传签章 生成订单
     *
     * @param purchaseContracts
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSignature(PurchaseContracts purchaseContracts) {
        PurchaseContracts oldContract = baseMapper.selectById(purchaseContracts.getId());
        //上传签章时 判断关联的审批流是否结束
        if (CommonConstant.TWO_STR.equals(purchaseContracts.getApproveStatus())) {
            throw new ServiceException(PurchaseErrorCode.NOT_NO_UNION_APPROVE.getCode(), PurchaseErrorCode.NOT_NO_UNION_APPROVE.getMsg());
        }
        //校验签章时流程是否结束
        FileBusiness fileBusiness = new FileBusiness();
        fileBusiness.setBusinessId(purchaseContracts.getId());
        fileBusiness.setAttribute(PURCHASE_QZFJ);
        fileApi.deleteByBusinessIdAndAttribute(fileBusiness);

        if (CollectionUtils.isNotEmpty(purchaseContracts.getQzhtFileIdList())) {
            fileBusiness.setFileIds(purchaseContracts.getQzhtFileIdList());
            fileApi.updateBusinessById(fileBusiness);
        }
        if (CommonConstant.ONE_STR.equals(oldContract.getQzStatus())) {
            //如果已经上传过就不更新状态
            oldContract.setQzStatus(CommonConstant.TWO_STR);
            baseMapper.updateById(oldContract);

            if (CommonConstant.ONE_STR.equals(oldContract.getContractType())) {
                PurchaseApprovalList purchaseApprovalList = purchaseApprovalListMapper.selectById(oldContract.getApproveId());
                //签章上传 生成采购订单
                PurchaseOrderDetails purchaseOrderDetails = new PurchaseOrderDetails();
                purchaseOrderDetails.setApplicant(purchaseApprovalList.getApplicant());
                purchaseOrderDetails.setApplicantId(purchaseApprovalList.getApplicantId());
                purchaseOrderDetails.setContractNumber(oldContract.getContractNumber());
                purchaseOrderDetails.setContractId(oldContract.getId());
                purchaseOrderDetails.setPurchaseOrderNumber(oldContract.getContractNumber());
                purchaseOrderDetails.setDeptId(purchaseApprovalList.getDeptId());
                purchaseOrderDetails.setDeptName(purchaseApprovalList.getDeptName());
                purchaseOrderDetails.setApplicationTime(LocalDateTime.now());
                purchaseOrderDetails.setSupplierName(oldContract.getSupplierName());
                purchaseOrderDetails.setSupplierId(oldContract.getSupplierId());
                purchaseOrderDetails.setAcceptor(purchaseApprovalList.getAcceptanceUserId());
                purchaseOrderDetails.setProjectNumber(purchaseApprovalList.getNumber());
                purchaseOrderDetails.setProjectName(purchaseApprovalList.getProjectName());
                purchaseOrderDetails.setOrderStatus(CommonConstant.ONE_STR);
                purchaseOrderDetails.setOverStatus(CommonConstant.ZERO_STR);
                purchaseOrderDetails.setPayStatus(CommonConstant.TWO_STR);
                purchaseOrderDetailsMapper.insert(purchaseOrderDetails);
                List<PurchaseContractProducts> products = gPurchaseContractProductsMapper.selectList(Wrappers.<PurchaseContractProducts>lambdaQuery().eq(PurchaseContractProducts::getContractId, purchaseContracts.getId()));
                if (CollectionUtils.isNotEmpty(products)) {
                    List<String> itemIds = products.stream().map(PurchaseContractProducts::getProductId).collect(Collectors.toList());
                    Map<String, String> itemTypeMap = null;
                    if (CollectionUtils.isNotEmpty(itemIds)) {
                        ResultBody<List<MaterialManagement>> materialRs = materialApi.getMaterialManagerByIds(itemIds);
                        if (materialRs != null && CollectionUtils.isNotEmpty(materialRs.getData())) {
                            itemTypeMap = materialRs.getData().stream().collect(Collectors.toMap(MaterialManagement::getId, MaterialManagement::getWarehouseCode, (m1, m2) -> m1));
                        }
                    }

                    for (PurchaseContractProducts product : products) {
                        PurchaseRelatedProduct purchaseRelatedProduct = new PurchaseRelatedProduct();
                        BeanUtils.copyProperties(product, purchaseRelatedProduct);
                        purchaseRelatedProduct.setItemName(product.getProductName());
                        if (itemTypeMap != null) {
                            purchaseRelatedProduct.setItemType(itemTypeMap.get(product.getProductId()));
                        }
                        purchaseRelatedProduct.setItemId(product.getProductId());
                        purchaseRelatedProduct.setItemCode(product.getProductCode());
                        purchaseRelatedProduct.setSpecificationModel(product.getSpecificationModel());
                        purchaseRelatedProduct.setDetailId(purchaseOrderDetails.getId());
                        purchaseRelatedProduct.setQuantity(product.getQuantity());
                        purchaseRelatedProduct.setInitQuantity(product.getQuantity());
                        purchaseRelatedProduct.setId(null);
                        purchaseRelatedProductMapper.insert(purchaseRelatedProduct);
                    }
                }
            }
        }
    }

    @Override
    public void processStart(BpmProcessInstanceCreate bpmProcessInstanceCreate) {
        Map<String, Object> variables = new HashMap<>();
        String userId = commonService.getUser().getUserId();
        variables.put(Constants.PROCESS_INSTANCE_STARTER_USER_ID, userId);
        variables.put(Constants.PROCESS_INSTANCE_BUSINESS_KEY, bpmProcessInstanceCreate.getBusinessKey());
        variables.put(Constants.PROCESS_INSTANCE_MENU_ID, bpmProcessInstanceCreate.getMenuId());
        bpmProcessInstanceCreate.setVariables(variables);
        String processId = commonService.startProcess(bpmProcessInstanceCreate);
        if (StringUtils.isNotBlank(processId)) {
            BpmTaskApproveReq bpmTaskApproveReq = new BpmTaskApproveReq();
            bpmTaskApproveReq.setId(processId);
            bpmTaskApproveReq.setUserId(userId);
            camundaApi.approve(bpmTaskApproveReq);
        }
    }

    @Override
    public void processNotice(String businessId) {
        ResultBody<List<BpmProcessInstanceStatus>> resultBody = camundaApi.queryProcessInstanceStatus(Arrays.asList(businessId));
        if (resultBody != null && CollectionUtils.isNotEmpty(resultBody.getData())) {
            BpmProcessInstanceStatus process = resultBody.getData().get(0);
            if (process.getNodeKey().equals(FINISH_NODE_KEY)) {
                PurchaseContracts purchaseContracts = baseMapper.selectById(businessId);
                if (purchaseContracts != null) {
                    purchaseContracts.setApproveStatus(CommonConstant.TWO_STR);
                    this.updateById(purchaseContracts);
                }
            }
        }
    }

    @Override
    public String getChildNumber(PurchaseContracts contracts) {
        String sequenceNumber = "";
        if (contracts != null && StringUtils.isNotBlank(contracts.getContractNumber())) {
            sequenceNumber = baseMapper.getChildNumber(contracts.getContractNumber());
            if (StringUtils.isNotBlank(sequenceNumber)) {
                String sequence = sequenceNumber.replace(contracts.getContractNumber(), "");
                if (StringUtils.isNotBlank(sequence)) {
                    String seq = sequence.substring(1);
                    int seqInt = Integer.parseInt(seq);
                    seqInt++;
                    sequenceNumber = sequenceNumber.concat("-" + seqInt);
                } else {
                    sequenceNumber = sequenceNumber.concat("-1");
                }
            }
        }

        return sequenceNumber;
    }

    @Override
    public void batchDelete(List<String> ids) {
        List<PurchaseContracts> contracts = this.list(Wrappers.<PurchaseContracts>lambdaQuery().in(PurchaseContracts::getId,ids));
        if(CollectionUtils.isNotEmpty(contracts)){
            for (PurchaseContracts contract : contracts) {
                reportBiddersMapper.updateReportUsed(contract.getProjectNumber(), contract.getSupplierId(),Constants.ZERO_STR);
                purchaseApprovalListMapper.updateApprovalSupplier(contract.getProjectNumber(), contract.getSupplierId(),Constants.ZERO_STR);
            }
        }
        this.removeBatchByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGPurchaseContracts(PurchaseContracts purchaseContracts) {
        PurchaseContracts oldData = this.getById(purchaseContracts.getId());
        baseMapper.updateById(purchaseContracts);
        if(!CommonConstant.ONE_STR.equals(purchaseContracts.getIsSupplement())){
            fileApi.deleteByBusinessId(purchaseContracts.getId());
        }
        //判断当前数据供应商与修改供应商是否是同一个
        String supplierId = purchaseContracts.getSupplierId();
        if (oldData != null) {
            if (!supplierId.equals(oldData.getSupplierId())) {
                purchaseApprovalSupplierService.updateIsUsedById(oldData.getApproveId(),oldData.getSupplierId(),Constants.ZERO_STR);
                purchaseApprovalSupplierService.updateIsUsedById(purchaseContracts.getApproveId(),supplierId,Constants.ONE_STR);
            }
        }

        if (CommonConstant.ZERO_STR.equals(purchaseContracts.getApproveStatus())) {
            purchaseContracts.setApproveStatus(CommonConstant.ONE_STR);
        }
        if (CollectionUtils.isNotEmpty(purchaseContracts.getHtfjFileIdList())) {
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setAttribute(PURCHASE_HTFJ);
            fileBusiness.setFileIds(purchaseContracts.getHtfjFileIdList());
            fileBusiness.setBusinessId(purchaseContracts.getId());
            fileApi.updateBusinessById(fileBusiness);
        }
        if (CollectionUtils.isNotEmpty(purchaseContracts.getDeleteFileList())) {
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setAttribute(PURCHASE_DELETE_FILE);
            fileBusiness.setFileIds(purchaseContracts.getDeleteFileList());
            fileBusiness.setBusinessId(purchaseContracts.getId());
            fileApi.updateBusinessById(fileBusiness);
        }

        if (CollectionUtils.isNotEmpty(purchaseContracts.getZbsmFileIdList())) {
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setAttribute(PURCHASE_ZBSM);
            fileBusiness.setFileIds(purchaseContracts.getZbsmFileIdList());
            fileBusiness.setBusinessId(purchaseContracts.getId());
            fileApi.updateBusinessById(fileBusiness);
        }

        if (CollectionUtils.isNotEmpty(purchaseContracts.getZbfjFileIdList())) {
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setAttribute(PURCHASE_ZBFJ);
            fileBusiness.setFileIds(purchaseContracts.getZbfjFileIdList());
            fileBusiness.setBusinessId(purchaseContracts.getId());
            fileApi.updateBusinessById(fileBusiness);
        }
        if(CommonConstant.ONE_STR.equals(purchaseContracts.getIsSupplement())){
           List<PurchaseContractProducts> oldProducts = gPurchaseContractProductsMapper.selectList(Wrappers.<PurchaseContractProducts>lambdaQuery().eq(PurchaseContractProducts::getContractId, purchaseContracts.getId()));
           Map<String,String> productIdMap = oldProducts.stream().collect(Collectors.toMap(p1->p1.getId(),p1->p1.getId(),(p1,p2)->p1));
           if(CollectionUtils.isNotEmpty(purchaseContracts.getPurchaseContractProductsList())){
               List<PurchaseContractProducts> newProducts = new ArrayList<>();
               for (PurchaseContractProducts product : purchaseContracts.getPurchaseContractProductsList()) {
                   if(productIdMap.get(product.getId())==null){
                       newProducts.add(product);
                   }
               }

               if(CollectionUtils.isNotEmpty(newProducts)){
                   //更新到采购定单物品关联表
                   if (CommonConstant.ONE_STR.equals(purchaseContracts.getContractType())) {
                       PurchaseApprovalList purchaseApprovalList = purchaseApprovalListMapper.selectById(purchaseContracts.getApproveId());
                       //签章上传 生成采购订单
                       PurchaseOrderDetails purchaseOrderDetails = new PurchaseOrderDetails();
                       purchaseOrderDetails.setApplicant(purchaseApprovalList.getApplicant());
                       purchaseOrderDetails.setApplicantId(purchaseApprovalList.getApplicantId());
                       purchaseOrderDetails.setContractNumber(purchaseContracts.getContractNumber());
                       purchaseOrderDetails.setContractId(purchaseContracts.getId());
                       purchaseOrderDetails.setPurchaseOrderNumber(purchaseContracts.getContractNumber());
                       purchaseOrderDetails.setDeptId(purchaseApprovalList.getDeptId());
                       purchaseOrderDetails.setDeptName(purchaseApprovalList.getDeptName());
                       purchaseOrderDetails.setApplicationTime(LocalDateTime.now());
                       purchaseOrderDetails.setSupplierName(purchaseContracts.getSupplierName());
                       purchaseOrderDetails.setSupplierId(purchaseContracts.getSupplierId());
                       purchaseOrderDetails.setAcceptor(purchaseApprovalList.getAcceptanceUserId());
                       purchaseOrderDetails.setProjectNumber(purchaseApprovalList.getApplyNumber());
                       purchaseOrderDetails.setProjectName(purchaseApprovalList.getProjectName());
                       purchaseOrderDetails.setOrderStatus(CommonConstant.ONE_STR);
                       purchaseOrderDetails.setOverStatus(CommonConstant.ZERO_STR);
                       purchaseOrderDetails.setPayStatus(CommonConstant.TWO_STR);
                       purchaseOrderDetailsMapper.insert(purchaseOrderDetails);

                       List<String> itemIds = newProducts.stream().map(PurchaseContractProducts::getProductId).collect(Collectors.toList());
                       Map<String, String> itemTypeMap = null;
                       if (CollectionUtils.isNotEmpty(itemIds)) {
                           ResultBody<List<MaterialManagement>> materialRs = materialApi.getMaterialManagerByIds(itemIds);
                           if (materialRs != null && CollectionUtils.isNotEmpty(materialRs.getData())) {
                               itemTypeMap = materialRs.getData().stream().collect(Collectors.toMap(MaterialManagement::getId, MaterialManagement::getWarehouseCode, (m1, m2) -> m1));
                           }
                       }

                       for (PurchaseContractProducts product : newProducts) {
                           PurchaseRelatedProduct purchaseRelatedProduct = new PurchaseRelatedProduct();
                           BeanUtils.copyProperties(product, purchaseRelatedProduct);
                           purchaseRelatedProduct.setItemName(product.getProductName());
                           if (itemTypeMap != null) {
                               purchaseRelatedProduct.setItemType(itemTypeMap.get(product.getProductId()));
                           }
                           purchaseRelatedProduct.setItemId(product.getProductId());
                           purchaseRelatedProduct.setItemCode(product.getProductCode());
                           purchaseRelatedProduct.setSpecificationModel(product.getSpecificationModel());
                           purchaseRelatedProduct.setDetailId(purchaseOrderDetails.getId());
                           purchaseRelatedProduct.setQuantity(product.getQuantity());
                           purchaseRelatedProduct.setInitQuantity(product.getQuantity());
                           purchaseRelatedProduct.setId(null);
                           purchaseRelatedProductMapper.insert(purchaseRelatedProduct);
                       }
                   }
               }
           }
        }

        gPurchaseContractProductsMapper.delete(Wrappers.<PurchaseContractProducts>lambdaQuery().eq(PurchaseContractProducts::getContractId, purchaseContracts.getId()));
        if (CollectionUtils.isNotEmpty(purchaseContracts.getPurchaseContractProductsList())) {
            for (PurchaseContractProducts purchaseContractProducts : purchaseContracts.getPurchaseContractProductsList()) {
                purchaseContractProducts.setContractId(purchaseContracts.getId());
                gPurchaseContractProductsMapper.insert(purchaseContractProducts);
            }
        }
    }

    @Override
    public void addAbolishFile(PurchaseContracts purchaseContracts) {
        if (StringUtils.isNotBlank(purchaseContracts.getId())) {
            PurchaseContracts contracts = this.getById(purchaseContracts.getId());
            if (contracts != null) {
                contracts.setDeleteStatus(CommonConstant.TWO_STR);
                this.updateById(contracts);
            }
            if (CollectionUtils.isNotEmpty(purchaseContracts.getDeleteFileList())) {
                FileBusiness fileBusiness = new FileBusiness();
                fileBusiness.setAttribute(PURCHASE_DELETE_FILE);
                fileBusiness.setFileIds(purchaseContracts.getDeleteFileList());
                fileBusiness.setBusinessId(purchaseContracts.getId());
                fileApi.updateBusinessById(fileBusiness);
            }
        }

    }

    @Override
    public PurchaseContracts getOneById(String id) {
        PurchaseContracts gPurchaseContracts = baseMapper.selectById(id);
        if(gPurchaseContracts!=null) {
            Object userNameObj = redisService.hget(RedisKey.USER_GROUP_TYPE, gPurchaseContracts.getReceiver());
            if (userNameObj != null) {
                gPurchaseContracts.setReceiverName(userNameObj.toString());
            }

            ResultBody<List<FileBusiness>> fileBusinessesRs = fileApi.getFileBusinessByIds(Arrays.asList(id));
            if (fileBusinessesRs != null && CollectionUtils.isNotEmpty(fileBusinessesRs.getData())) {
                Map<String, FileBusiness> fileBusinessMap = fileBusinessesRs.getData().stream().collect(Collectors.toMap(FileBusiness::getBusinessId, fb -> fb, (f1, f2) -> f1));
                List<String> fileIds = new ArrayList<>();
                FileBusiness fileBusiness = fileBusinessMap.get(gPurchaseContracts.getId().concat(PURCHASE_HTFJ));
                if (fileBusiness != null) {
                    if (CollectionUtils.isNotEmpty(fileBusiness.getFileIds())) {
                        fileIds.addAll(fileBusiness.getFileIds());
                    }
                }
                fileBusiness = fileBusinessMap.get(gPurchaseContracts.getId().concat(PURCHASE_QZFJ));
                if (fileBusiness != null) {
                    fileIds.addAll(fileBusiness.getFileIds());
                }
                gPurchaseContracts.setHtfjFileIdList(fileIds);

                fileBusiness = fileBusinessMap.get(gPurchaseContracts.getId().concat(PURCHASE_ZBSM));
                if (fileBusiness != null) {
                    gPurchaseContracts.setZbsmFileIdList(fileBusiness.getFileIds());
                }
                fileBusiness = fileBusinessMap.get(gPurchaseContracts.getId().concat(PURCHASE_ZBFJ));
                if (fileBusiness != null) {
                    gPurchaseContracts.setZbfjFileIdList(fileBusiness.getFileIds());
                }
                fileBusiness = fileBusinessMap.get(gPurchaseContracts.getId().concat(PURCHASE_DELETE_FILE));
                if (fileBusiness != null) {
                    gPurchaseContracts.setDeleteFileList(fileBusiness.getFileIds());
                }
                fileBusiness = fileBusinessMap.get(gPurchaseContracts.getId().concat(PURCHASE_QZFJ));
                if (fileBusiness != null) {
                    gPurchaseContracts.setQzhtFileIdList(fileBusiness.getFileIds());
                }
            }
            List<PurchaseContractProducts> gPurchaseContractProducts = gPurchaseContractProductsMapper.selectList(Wrappers.<PurchaseContractProducts>lambdaQuery().eq(PurchaseContractProducts::getContractId, id));
            gPurchaseContracts.setPurchaseContractProductsList(gPurchaseContractProducts);
        }
        return gPurchaseContracts;
    }
}
